480C - Riding in a Lift - CodeForces Solution


combinatorics dp implementation *1900

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int>PII;
#define x first
#define y second
typedef long long ll;
const int N=5010,mod=1e9+7;
int T,n,a,b,k;  //第i次在j位置的方案数
void add(int a,int b,int c,int diff[]){ //区间[a,b)
    diff[a]=(diff[a]+c)%mod;
    diff[b]=(diff[b]-c+mod)%mod;
}
void solve(){
    cin>>n>>a>>b>>k;
    int diff[n+2];  //差分数组  x到y的范围为(x-d,x+d) 因此可以使用差分数组记录方案数
    memset(diff,0,sizeof diff);
    add(a,min(a+1,n+1),1,diff);  //起点初始化
    for(int i=1;i<=k;i++){
        vector<int>s(n+1,0);
        for(int j=1;j<=n;j++){
            s[j]=(s[j-1]+diff[j])%mod;
        }
        memset(diff,0,sizeof diff);  //初始化 清空上一轮的状态(不清空结果不对)
        for(int j=1;j<=n;j++){
            int d=abs(j-b);
            int l=max(1,j-d+1),r=min(n+1,j+d);
            //cout<<l<<" "<<r<<" "<<j<<" "<<s[j]<<endl;
            add(l,j,s[j],diff);   //不能停在原点 因此分成两部分计算
            add(j+1,r,s[j],diff);
        }
    }
    ll res=0,pre=0;
    for(int i=1;i<=n;i++){  //统计终点在[1,n]的方案数
       pre=(pre+diff[i]+mod)%mod;
       res=(res+pre)%mod;
       //cout<<diff[i]<<" ";
    }
    cout<<res<<endl;
}
int main(){
    T=1;
    //cin>>T;
    while(T--){
        solve();
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

137. Single Number II
130. Surrounded Regions
129. Sum Root to Leaf Numbers
120. Triangle
102. Binary Tree Level Order Traversal
96. Unique Binary Search Trees
75. Sort Colors
74. Search a 2D Matrix
71. Simplify Path
62. Unique Paths
50. Pow(x, n)
43. Multiply Strings
34. Find First and Last Position of Element in Sorted Array
33. Search in Rotated Sorted Array
17. Letter Combinations of a Phone Number
5. Longest Palindromic Substring
3. Longest Substring Without Repeating Characters
1312. Minimum Insertion Steps to Make a String Palindrome
1092. Shortest Common Supersequence
1044. Longest Duplicate Substring
1032. Stream of Characters
987. Vertical Order Traversal of a Binary Tree
952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder
123. Best Time to Buy and Sell Stock III
85. Maximal Rectangle
84. Largest Rectangle in Histogram
60. Permutation Sequence